﻿
using DevExpress.Internal.WinApi.Windows.UI.Notifications;
using DevExpress.Mvvm;
using DevExpress.Portable;
using HandyControl.Controls;
using HandyControl.Tools.Extension;
using log4net;
using Microsoft.VisualBasic.Logging;
using PlaceOrder_Core.Helper;
using PlaceOrder_Core.Models.QuanYi;
using PlaceOrder_Core.PlaceOrderModels;
using PlaceOrder_Core.Services.Instances;
using PlaceOrder_Core.Services.Interfaces;
using PlaceOrder_Shared.Models.Common;
using Prism.Mvvm;
using System;
using System.CodeDom;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Net.WebSockets;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using static System.Runtime.CompilerServices.RuntimeHelpers;
using MessageBox = HandyControl.Controls.MessageBox;

namespace PlaceOrder_Client.ViewModels
{
    public class ChangePriceViewModel:Prism.Mvvm.BindableBase
    {
        


        private decimal OriginalPrice;//初始价格
        private decimal OriginalVolume;//初始量
        private UserTrade QCT; //传进来的初始值
        private UserTrade userTrade;
        private Guid CurrentGuid;//生成的guid
        private bool bIsConnected = false;
        private bool bResponseReceived = false;
        private ClientWebSocketHelper clientWebsocket;
        private QuanYiOrderServerResponseClass GlobalQSR = new QuanYiOrderServerResponseClass();

        private bool bWaitingforResponse = false;


        #region 依赖属性
        private string brokerName;

        public string BrokerName
        {
            get { return brokerName; }
            set { brokerName = value;RaisePropertyChanged(); }
        }


        private bool selectedOptionJia0;

        /// <summary>
        /// +0  默认加0 
        /// </summary>
        public bool SelectedOptionJia0
        {
            get { return selectedOptionJia0; }
            set { selectedOptionJia0 = value;RaisePropertyChanged(); }
        }

        private bool selectedOptionJia1;

        /// <summary>
        /// +1 
        /// </summary>
        public bool SelectedOptionJia1
        {
            get { return selectedOptionJia1; }
            set { selectedOptionJia1 = value; RaisePropertyChanged(); }
        }

        private DateTime time;

        /// <summary>
        /// 下单时间
        /// </summary>
        public DateTime Time
        {
            get { return time; }
            set { time = value;RaisePropertyChanged(); }
        }

        private bool isLoading=false;

        public bool IsLoading
        {
            get { return isLoading; }
            set { isLoading= value;RaisePropertyChanged(); }
        }


        /// <summary>
        /// 状态显示
        /// </summary>
        private string status;

        public string Status
        {
            get { return status; }
            set { status = value;RaisePropertyChanged(); }
        }


        /// <summary>
        /// 券号
        /// </summary>
        private string bondNum;

		public string BondNum
        {
			get { return bondNum; }
			set { bondNum = value;RaisePropertyChanged(); }
		}


        /// <summary>
        /// 询量
        /// </summary>
        private int volume;

        public int Volume
        {
            get { return volume; }
            set { volume = value; RaisePropertyChanged(); }
        }

        /// <summary>
        /// 剩余询量
        /// </summary>
        private int restVolume;

        public int RestVolume
        {
            get { return restVolume; }
            set { restVolume = value; RaisePropertyChanged(); }
        }

        /// <summary>
        /// 交割日
        /// </summary>
        private DateTime? deliveryDate;

        public DateTime? DeliveryDate
        {
            get { return deliveryDate; }
            set { deliveryDate = value; RaisePropertyChanged(); }
        }

        /// <summary>
        /// 方向
        /// </summary>
        private string direction;

        public string Direction
        {
            get { return direction; }
            set { direction = value; RaisePropertyChanged(); }
        }

        /// <summary>
        /// 中介
        /// </summary>
        private string broker;

        public string Broker
        {
            get { return broker; }
            set { broker = value; RaisePropertyChanged(); }
        }

        /// <summary>
        /// 价格
        /// </summary>
        private decimal price;

        public decimal Price
        {
            get { return price; }
            set { price = value; RaisePropertyChanged(); }
        }

        private string dealType;


        public string DealType
        {
            get { return dealType; }
            set { dealType = value;RaisePropertyChanged(); }
        }

        #endregion

        private readonly IDailyData _dailyData;
        public ChangePriceViewModel(IDailyData dailyData)
        {
            _dailyData = dailyData;
     
        }

        public UserTrade TempTrade { get; set; }
        // 定义事件
        public event EventHandler<ChangePriceArgs> ChangePriceRequested;
        public ChangePriceViewModel(UserTrade Utrade)
        {
            if(Utrade==null)
            {
                return;
            }

            this.BrokerName = Utrade.Target;
            SelectedOptionJia0 = true;//默认是加0 ，后面再改
            TempTrade = Utrade;
            SubmitCommand = new DelegateCommand(ChangePrice);
            UserTrade trade = Utrade;
            this.Time = Utrade.Time;
            QCT =  trade;
            userTrade = trade;
            BondNum = trade.TsCode;
            DealType = trade.DealType;
            Price = trade.Price;
            DeliveryDate = new DateTime(trade.DeliveryDate.Year, trade.DeliveryDate.Month, trade.DeliveryDate.Day);
            Direction = trade.DealType;
            if (trade.DealType == "bid"||trade.DealType=="买入")
            {
                Direction = "买入";
            }
            else if (trade.DealType == "ofr" || trade.DealType == "卖出")
            {
                Direction = "卖出";
            }

            if(trade.OnHoldVolume!=0)
            {
                Volume = trade.OnHoldVolume;
                RestVolume = trade.OnHoldVolume;
                OriginalVolume = trade.OnHoldVolume;
            }else
            {
                Volume = trade.Volume;
                RestVolume = trade.OnHoldVolume;
                OriginalVolume = trade.Volume;
            }
            
            Broker = trade.Broker;
            OriginalPrice = trade.Price;
        
        }

        private void ChangePrice()
        {
            decimal price = 0;
            decimal volume = 0;
            if (!decimal.TryParse(Price.ToString(), out price))
            {
                Growl.WarningGlobal("请输入合法的价格!");
                return;
            }
            if (!decimal.TryParse(Volume.ToString(), out volume))
            {
                Growl.WarningGlobal("请输入合法的量!");
                return;
            }
            if (OriginalPrice == price&&OriginalVolume == volume)
            {
                Growl.WarningGlobal("报价/量 都未变更，请检查");
                return;
            }

            var newTrade = new UserTrade();
            newTrade = QCT;
            newTrade.Price = Price;
            newTrade.Volume = Volume;
            newTrade.BrokerID=TempTrade.BrokerID;
            newTrade.ChatID = TempTrade.UserID.ToString();
            ChangePriceRequested?.Invoke(this, new ChangePriceArgs(newTrade));

            Messenger.Default.Send(new string("1"));
            //IsLoading=true;
            //if (SendModify())
            //{
            //    Close();
            //    IsLoading = false;
            //}
        }

        private void Close()
        {
            Messenger.Default.Send(new string("1"));
        }

        public void SetTradeInfo(UserTrade trade)
        {
            QCT = trade;
            userTrade = trade;
            BondNum = trade.TsCode;
            DealType = trade.DealType;
            Price = trade.Price;
            DeliveryDate = new DateTime(trade.DeliveryDate.Year, trade.DeliveryDate.Month, trade.DeliveryDate.Day);
            Volume = trade.Volume;
            Broker = trade.Broker;
            OriginalPrice = trade.Price;
            OriginalVolume = trade.Volume;
        }
        #region 命令
        public DelegateCommand SubmitCommand { get; set; }//提交
        public DelegateCommand CancelCommand { get; set; }//取消
        #endregion

        #region 主要方法
        private bool SendModify()
        {

            string order = $"{userTrade.DealType} {userTrade.TsCode.Replace(".IB", "")} 改 {Price}";
            var result = MessageBox.Show("是否改价？ \r\n" + order.Replace("{ADD}", "+"), "确认", MessageBoxButton.YesNo, MessageBoxImage.Question);
            if(result == MessageBoxResult.No)
            {
                AppLog.WriteInfo("用户取消改价了");
                return false;
            }
            QuanYiOrderServerResponseClass qsr = new QuanYiOrderServerResponseClass();
            CurrentGuid = Guid.NewGuid();
            qsr.DataType = QuanYiServerBaseClass.DataTypeEnum.ChangePrice;
            QCT.Command = order;
            QCT.Price = Price;
            qsr.Trade = QCT;
            qsr.Guid = CurrentGuid;
            qsr.Token = UserHelper.Token;
            string msg;
            try
            {
                Status = "正在发送指令";
                if (bIsConnected)
                {
                    Status = "发送中...";

                    bResponseReceived = false;
                    clientWebsocket.SendResponseToServer(qsr);
                    IsLoading = true;
                    Task.Run(() =>
                    {
                        WaitingResponseThread();
                    });
                }
                else
                {
                    Status = "无法连接发送服务器，请联系管理员";
                    AppLog.WriteError($"下单：微信下单失败,{QCT.Command},{QCT.Target}");
                    return false;
                }
            }
            catch
            {
                MessageBox.Show("无法连接服务器，请联系管理员！", "Error");
                Status = "无法连接发送服务器，请联系管理员";
                AppLog.WriteError($"下单：微信下单失败,{QCT.Command},{QCT.Target}");
                return false;
            }

            Status = "指令已发送至中介，等待中介反馈";
            return false;
            //var result1 = MessageBox.Show("中介是否允许改价？", "确认", MessageBoxButton.YesNo, MessageBoxImage.Question);
            //if (result1 == MessageBoxResult.No)
            //{
            //    Status = "中介拒绝改价";
            //    Price = OriginalPrice;
            //    Volume = (int)OriginalVolume;
            //    QCT.Price = OriginalPrice;
            //    QCT.Volume = (int)OriginalVolume;
            //    AppLog.WriteInfo($"中介拒绝改价,{QCT.Command},{QCT.Target}"+userTrade.UserTradeID.ToString());
            //    return false;
            //}else
            //{
            //    Status = "中介同意改价，修改Lily询价单";
            //    CurrentGuid = Guid.NewGuid();
            //    qsr.DataType = QuanYiServerBaseClass.DataTypeEnum.ChangePriceConfirm;
            //    qsr.Code = 0;
            //    qsr.Trade = QCT;
            //    qsr.Token = UserHelper.Token;
            //    qsr.Guid = CurrentGuid;
            //}
   
            
            //try
            //{
            //    if (bIsConnected)
            //    {
            //        bResponseReceived = false;
            //        clientWebsocket.SendResponseToServer(qsr);
            //        Task.Run(() =>
            //        {
            //            WaitingResponseThread();
            //        });
            //    }
            //    else
            //    {
            //        Status = "无法连接发送服务器，请联系管理员";
            //        AppLog.WriteError($"下单：微信下单失败,{QCT.Command},{QCT.Target}");
            //        return false;
            //    }
            //}
            //catch
            //{
            //    Growl.ErrorGlobal("无法连接服务器，请联系管理员！");
            //    Status = "无法连接发送服务器，请联系管理员";
            //    AppLog.WriteError($"下单：微信下单失败,{QCT.Command},{QCT.Target}");
            //    return false;
            //}
            //return true;
        }

        private void WaitingResponseThread()
        {
            DateTime dtStart = DateTime.Now;
            TimeSpan ts = new TimeSpan();
            ts = DateTime.Now - dtStart;
            while (ts.TotalSeconds < ClientWebSocketHelper.GlobalTimeOut)
            {
                if (bResponseReceived)
                {
                    if (GlobalQSR.Code == 0)
                    {
                            QCT.Id = GlobalQSR.Trade.Id;
                            QCT.Time = GlobalQSR.Trade.Time;
                            bWaitingforResponse = false;
                    }
                    else
                    {
                        bWaitingforResponse = false;
                        MessageBox.Show(GlobalQSR.Message, "信息");


                    }
                    return;
                }
                Task.Delay(200).Wait();
                ts = DateTime.Now - dtStart;
            }
            bWaitingforResponse = false;
            MessageBox.Show("连接服务器超时", "信息");
        }
        #endregion
    }

    public class ChangePriceArgs : EventArgs
    {
        public UserTrade Trade { get; private set; }

        public ChangePriceArgs(UserTrade trade)
        {
            Trade = trade;
        }
    }

    public class PingCangArgs : EventArgs
    {
        public UserTrade Trade { get; private set; }

        public PingCangArgs(UserTrade trade)
        {
            Trade = trade;
        }
    }
}
